//
//  NSString+extend.m
//  basic
//
//  Created by Jack on 2016/12/13.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "NSString+extend.h"
//#import "NSData+extend.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (extend)

+ (NSString *)shortedNumberDesc:(NSInteger)number {
    // should be localized
    if (number <= 9999) return [NSString stringWithFormat:@"%d", (int)number];
    if (number <= 9999999) return [NSString stringWithFormat:@"%.1f万", (float)(number / 10000)];
    return [NSString stringWithFormat:@"%d千万", (int)(number / 10000000)];
}


+ (BOOL)checkPassword:(NSString *)pass
{
    if ([NSString isNotEmpty:pass]) {
        if (pass.length >=6 && pass.length <= 20) {
            return YES;
        }
    }
    return NO;
}

+ (NSString *)encrypPhoneNum:(NSString *)phone
{
    if ([NSString isNotEmpty:phone]) {
        if ([NSString isValidateMobile:phone]) {
            NSString *phone_ = [phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            return phone_;
        }
    }
    return phone;
}

+ (NSString *)encrypBankcard:(NSString *)bankcard
{
    if ([NSString isNotEmpty:bankcard]) {
        
        if (bankcard.length >= 4) {
            NSString *bankcard_ = [bankcard stringByReplacingCharactersInRange:NSMakeRange(0, bankcard.length-4) withString:@"****"];
            return bankcard_;
        }
    }
    return bankcard;
}


// 判断手机或者电话号码是否正确
+ (BOOL)isValidateMobile:(NSString *)mobile
{
    //手机号以13，14，15，17，18开头，八个 \d 数字字符
//    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9])||(17[0,6-8])|(14[5,7]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //固话不加区号的
    NSString * CT1 = @"^(0[0-9]{2,3}/-)?([2-9][0-9]{6,7})+(/-[0-9]{1,4})?$";
    NSPredicate *regextestct1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT1];
    //固话加区号的
    NSString * CT2 = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestct2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT2];
    
    if ([phoneTest evaluateWithObject:mobile] || [regextestct1 evaluateWithObject:mobile] || [regextestct2 evaluateWithObject:mobile])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}


//邮箱
+ (BOOL)isValidateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//身份证号
+ (BOOL)isValidateIdentityCard:(NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}


- (BOOL)isEqualToStr:(NSString *)string
{
    if ([NSString isNotEmpty:self] && [NSString isNotEmpty:string]) {
        if ([self isEqualToString:string]) {
            return YES;
        }
    }
    return NO;
}

- (NSData *)cutSoapNail
{
    NSString *string = [self stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body><getItemListResponse xmlns=\"http://tempuri.org/\" /></soap:Body></soap:Envelope>" withString:@""];
    
    return [string dataUsingEncoding:NSUTF8StringEncoding];
}

+ (NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim
{
    NSString *htmlStr = html;
    NSScanner *theScanner = [NSScanner scannerWithString:htmlStr];
    NSString *text = nil;
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        htmlStr = [htmlStr stringByReplacingOccurrencesOfString:
                [NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    return trim ? [htmlStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : htmlStr;
}

+ (NSString *) getOtherdayTime:(NSDate *)time
{
    static NSDateFormatter *dateFormatter = nil;
    
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd ah:mm"];
    }
    return [dateFormatter stringFromDate:time];
}

+ (NSString *) getOtherday2Time:(NSDate *)time
{
    static NSDateFormatter *dateFormatter = nil;
    
    if (dateFormatter == nil) {
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }
    return [dateFormatter stringFromDate:time];
}

+ (NSString *)comeName:(NSString *)name{
    
    NSMutableString  * testPhoneStr;
    if(name){//判断用户名是否为空
        testPhoneStr= [ NSMutableString   stringWithString : name ];
        
        NSRange range= NSMakeRange (3,name.length-7);
        if  (testPhoneStr.length  > range. length ) {
            [testPhoneStr  replaceCharactersInRange :range  withString : @"****" ];
        }
    }
    return testPhoneStr;

}
+ (BOOL)isNotEmpty:(NSString *)string
{
    if (string && ![string isEqual:[NSNull null]]) {
        
        if ([string isKindOfClass:[NSString class]] && string.length > 0) {
            
            if ([string isEqualToString:@"<null>"]) {
                return NO;
            }
            return YES;
        }
    }
    return NO;
}

+ (CGSize)calculateTextHeight:(UIFont *)fonts givenText:(NSString *)texts givenWidth:(CGFloat)width
{
    if (![NSString isNotEmpty:texts]) {
        return CGSizeZero;
    }
    
    CGSize size = [texts sizeWithFont:fonts constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
    return CGSizeMake(size.width+2, size.height+2);
}

+ (CGSize)calculateTextWidth:(UIFont *)fonts givenText:(NSString *)texts givenWidth:(CGFloat)width  givenHeight:(CGFloat)height{
    if (![NSString isNotEmpty:texts]) {
        return CGSizeZero;
    }
 
    CGSize size = [texts sizeWithFont:fonts constrainedToSize:CGSizeMake(width, height) lineBreakMode:NSLineBreakByWordWrapping];
    return CGSizeMake(size.width+2, size.height+2);
}


+ (CGSize)calculateTextWidth:(UIFont *)fonts givenText:(NSString *)texts givenWidth:(CGFloat)width{
    
    return [self calculateTextWidth:fonts givenText:texts givenWidth:width givenHeight:20];
}

+ (CGSize)calculateTextWidth:(UIFont *)fonts givenText:(NSString *)texts{
    
    return [self calculateTextWidth:fonts givenText:texts givenWidth:kMainScreenWidth];
}

- (BOOL)containsString:(NSString *)string {
	return !NSEqualRanges([self rangeOfString:string], NSMakeRange(NSNotFound, 0));
}

//- (NSString *)MD5SumStr {
//	const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
//	NSData *data = [NSData dataWithBytes:cstr length:self.length];
//	return [data MD5SumStr];
//}
//
//
//- (NSString *)SHA1SumStr {
//	const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
//	NSData *data = [NSData dataWithBytes:cstr length:self.length];
//	return [data SHA1SumStr];
//}


// Adapted from http://snipplr.com/view/2771/compare-two-version-strings
- (NSComparisonResult)compareToVersionString:(NSString *)version {
	// Break version into fields (separated by '.')
	NSMutableArray *leftFields  = [[NSMutableArray alloc] initWithArray:[self  componentsSeparatedByString:@"."]];
	NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[version componentsSeparatedByString:@"."]];
	
	// Implict ".0" in case version doesn't have the same number of '.'
	if ([leftFields count] < [rightFields count]) {
		while ([leftFields count] != [rightFields count]) {
			[leftFields addObject:@"0"];
		}
	} else if ([leftFields count] > [rightFields count]) {
		while ([leftFields count] != [rightFields count]) {
			[rightFields addObject:@"0"];
		}
	}
	
	// Do a numeric comparison on each field
	for (NSUInteger i = 0; i < [leftFields count]; i++) {
		NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
		if (result != NSOrderedSame) {
			return result;
		}
	}
	
	return NSOrderedSame;
}


#pragma mark - HTML Methods

- (NSString *)escapeHTML {
	NSMutableString *s = [NSMutableString string];
	
	NSUInteger start = 0;
	NSUInteger len = [self length];
	NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"<>&\""];
	
	while (start < len) {
		NSRange r = [self rangeOfCharacterFromSet:chs options:0 range:NSMakeRange(start, len-start)];
		if (r.location == NSNotFound) {
			[s appendString:[self substringFromIndex:start]];
			break;
		}
		
		if (start < r.location) {
			[s appendString:[self substringWithRange:NSMakeRange(start, r.location-start)]];
		}
		
		switch ([self characterAtIndex:r.location]) {
			case '<':
				[s appendString:@"&lt;"];
				break;
			case '>':
				[s appendString:@"&gt;"];
				break;
			case '"':
				[s appendString:@"&quot;"];
				break;
                //			case '…':
                //				[s appendString:@"&hellip;"];
                //				break;
			case '&':
				[s appendString:@"&amp;"];
				break;
		}
		
		start = r.location + 1;
	}
	
	return s;
}


- (NSString *)unescapeHTML {
	NSMutableString *s = [NSMutableString string];
	NSMutableString *target = [self mutableCopy];
	NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"&"];
	
	while ([target length] > 0) {
		NSRange r = [target rangeOfCharacterFromSet:chs];
		if (r.location == NSNotFound) {
			[s appendString:target];
			break;
		}
		
		if (r.location > 0) {
			[s appendString:[target substringToIndex:r.location]];
			[target deleteCharactersInRange:NSMakeRange(0, r.location)];
		}
		
		if ([target hasPrefix:@"&lt;"]) {
			[s appendString:@"<"];
			[target deleteCharactersInRange:NSMakeRange(0, 4)];
		} else if ([target hasPrefix:@"&gt;"]) {
			[s appendString:@">"];
			[target deleteCharactersInRange:NSMakeRange(0, 4)];
		} else if ([target hasPrefix:@"&quot;"]) {
			[s appendString:@"\""];
			[target deleteCharactersInRange:NSMakeRange(0, 6)];
		} else if ([target hasPrefix:@"&#39;"]) {
			[s appendString:@"'"];
			[target deleteCharactersInRange:NSMakeRange(0, 5)];
		} else if ([target hasPrefix:@"&amp;"]) {
			[s appendString:@"&"];
			[target deleteCharactersInRange:NSMakeRange(0, 5)];
		} else if ([target hasPrefix:@"&hellip;"]) {
			[s appendString:@"…"];
			[target deleteCharactersInRange:NSMakeRange(0, 8)];
        } else if ([target hasPrefix:@"&nbsp;"]) {
			[s appendString:@""];
			[target deleteCharactersInRange:NSMakeRange(0, 6)];
        } else if ([target hasPrefix:@"&ldquo;"]) {
            [s appendString:@"“"];
            [target deleteCharactersInRange:NSMakeRange(0, 7)];
        } else if ([target hasPrefix:@"&rdquo;"]) {
            [s appendString:@"”"];
            [target deleteCharactersInRange:NSMakeRange(0, 7)];
        } else {
			[s appendString:@"&"];
			[target deleteCharactersInRange:NSMakeRange(0, 1)];
		}
	}
	
	return s;
}


#pragma mark - URL Escaping and Unescaping

- (NSString *)stringByEscapingForURLQuery {
	NSString *result = self;
    
	static CFStringRef leaveAlone = CFSTR(" ");
	static CFStringRef toEscape = CFSTR("\n\r:/=,!$&'()*+;[]@#?%");
    
	CFStringRef escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)self, leaveAlone,
																	 toEscape, kCFStringEncodingUTF8);
    
	if (escapedStr) {
		NSMutableString *mutable = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
		CFRelease(escapedStr);
        
		[mutable replaceOccurrencesOfString:@" " withString:@"+" options:0 range:NSMakeRange(0, [mutable length])];
		result = mutable;
	}
	return result;
}


- (NSString *)stringByUnescapingFromURLQuery {
	NSString *deplussed = [self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    return [deplussed stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


#pragma mark - URL Encoding and Unencoding (Deprecated)

- (NSString *)URLEncodedString {
	static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?%");
	return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
																				 (__bridge CFStringRef)self,
																				 NULL,
																				 toEscape,
																				 kCFStringEncodingUTF8);
}


- (NSString *)URLEncodedParameterString {
	static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?");
    return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
																				 (__bridge CFStringRef)self,
																				 NULL,
																				 toEscape,
																				 kCFStringEncodingUTF8);
}


- (NSString *)URLDecodedString {
	return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
																								 (__bridge CFStringRef)self,
																								 CFSTR(""),
																								 kCFStringEncodingUTF8);
}


#pragma mark - Base64 Encoding

//- (NSString *)base64EncodedString  {
//    if ([self length] == 0) {
//        return nil;
//	}
//	
//	return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
//}
//
//
//+ (NSString *)stringWithBase64String:(NSString *)base64String {
//	return [[NSString alloc] initWithData:[NSData dataWithBase64String:base64String] encoding:NSUTF8StringEncoding];
//}



#pragma mark - Generating a UUID

+ (NSString *)stringWithUUID {
	CFUUIDRef uuid = CFUUIDCreate(NULL);
	CFStringRef string = CFUUIDCreateString(NULL, uuid);
	CFRelease(uuid);
	return (__bridge_transfer NSString *)string;
}


#pragma mark - Trimming

- (NSString *)stringByTrimmingLeadingAndTrailingCharactersInSet:(NSCharacterSet *)characterSet {
	return [[self stringByTrimmingLeadingCharactersInSet:characterSet]
			stringByTrimmingTrailingCharactersInSet:characterSet];
}


- (NSString *)stringByTrimmingLeadingAndTrailingWhitespaceAndNewlineCharacters {
	return [[self stringByTrimmingLeadingWhitespaceAndNewlineCharacters]
			stringByTrimmingTrailingWhitespaceAndNewlineCharacters];
}


- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet {
    NSRange rangeOfFirstWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]];
    if (rangeOfFirstWantedCharacter.location == NSNotFound) {
        return @"";
    }
    return [self substringFromIndex:rangeOfFirstWantedCharacter.location];
}


- (NSString *)stringByTrimmingLeadingWhitespaceAndNewlineCharacters {
    return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}


- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
    NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
                                                               options:NSBackwardsSearch];
    if (rangeOfLastWantedCharacter.location == NSNotFound) {
        return @"";
    }
    return [self substringToIndex:rangeOfLastWantedCharacter.location + 1]; // Non-inclusive
}


- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
    return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)changeToFloatDigit
{
    if (![NSString isNotEmpty:self]) {
        return @"";
    }
    
    NSString *stringFloat = [NSString stringWithFormat:@"%0.2f",self.doubleValue];
    
    const char *floatChars = [stringFloat UTF8String];
    NSUInteger length = [stringFloat length];
    NSUInteger zeroLength = 0;
    int i = (int)length-1;
    for(; i>=0; i--)
    {
        if(floatChars[i] == '0'/*0x30*/) {
            zeroLength++;
        } else {
            if(floatChars[i] == '.')
                i--;
            break;
        }
    }
    NSString *returnString;
    if(i == -1) {
        returnString = @"0";
    } else {
        returnString = [stringFloat substringToIndex:i+1];
    }
    return returnString;
}

// 4个长度用空格分割
+ (NSString *)dividingTheDigital:(NSString *)digital
{
    NSInteger t = digital.length%4 > 0?digital.length/4 + 1:digital.length/4;
    
    NSMutableString *str = [NSMutableString stringWithString:digital];
    
    NSString *result = @"";
    
    for(int i = 0 ; i < t ; i ++){
        if (i != t - 1) {
            result = [NSString stringWithFormat:@"%@%@  ",result,[str substringToIndex:4]];
        }else{
            result = [NSString stringWithFormat:@"%@%@  ",result,str];
        }
        if (i != t -1) {
            [str deleteCharactersInRange:NSMakeRange(0, 4)];
        }
        
    }
    return  [result substringWithRange:NSMakeRange(0, result.length - 2)];
}


+ (NSString *)mobileEncryption:(NSString *)mobile{
    
    NSString *nickname = @"网友";
    
    if ([NSString isNotEmpty:mobile]) {
        
        nickname = mobile;
        
        
        if ([NSString isValidateMobile:nickname]) {
            
            
            nickname = [NSString stringWithFormat:@"%@****%@",[nickname substringToIndex:3],[nickname substringFromIndex:8]];
        }
        
        
    }

    return nickname;
}

@end
